<template>
  <div class="flex flex-col gap-3 flex-1">
    <!-- 顶部统计卡片 -->
    <div class="grid grid-cols-4 gap-4">
      <el-card v-for="stat in statistics" :key="stat.label" shadow="hover">
        <div class="flex items-center justify-between">
          <div class="flex flex-col">
            <span class="text-gray-500 text-sm">{{ stat.label }}</span>
            <span class="text-2xl font-bold mt-2" :class="stat.color">{{ stat.value }}</span>
            <span class="text-sm text-gray-400 mt-1">
              {{ stat.compare }}
              <span :class="stat.trend === 'up' ? 'text-red-500' : 'text-green-500'">
                {{ stat.percentage }}
              </span>
            </span>
          </div>
          <el-icon :size="40" :class="stat.iconColor">
            <component :is="stat.icon" />
          </el-icon>
        </div>
      </el-card>
    </div>

    <!-- 数据分析区域 -->
    <div class="grid grid-cols-2 gap-3">
      <!-- 患者来源分析 -->
      <el-card shadow="hover" class="h-[400px]">
        <template #header>
          <div class="flex justify-between items-center">
            <span class="font-bold">患者来源渠道分析</span>
            <el-select v-model="sourceTimeRange" class="w-32">
              <el-option label="最近7天" value="7" />
              <el-option label="最近30天" value="30" />
              <el-option label="最近90天" value="90" />
            </el-select>
          </div>
        </template>
        <div ref="sourceChartRef" class="w-full h-full"></div>
      </el-card>

      <!-- 就诊频率分析 -->
      <el-card shadow="hover" class="h-[400px]">
        <template #header>
          <div class="flex justify-between items-center">
            <span class="font-bold">就诊频率趋势</span>
            <el-radio-group v-model="visitFrequencyType" size="small">
              <el-radio-button :value="'daily'">日</el-radio-button>
              <el-radio-button :value="'weekly'">周</el-radio-button>
              <el-radio-button :value="'monthly'">月</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <div ref="frequencyChartRef" class="w-full h-full"></div>
      </el-card>

      <!-- 消费金额分析 -->
      <el-card shadow="hover" class="h-[400px]">
        <template #header>
          <div class="flex justify-between items-center">
            <span class="font-bold">患者消费分析</span>
            <el-select v-model="consumptionDepartment" class="w-32">
              <el-option label="全部科室" value="" />
              <el-option
                v-for="dept in departments"
                :key="dept.id"
                :label="dept.name"
                :value="dept.id"
              />
            </el-select>
          </div>
        </template>
        <div ref="consumptionChartRef" class="w-full h-full"></div>
      </el-card>

      <!-- 满意度分析 -->
      <el-card shadow="hover" class="h-[400px]">
        <template #header>
          <div class="flex justify-between items-center">
            <span class="font-bold">满意度分析</span>
            <el-select v-model="satisfactionDimension" class="w-32">
              <el-option label="整体满意度" value="overall" />
              <el-option label="医疗质量" value="medical" />
              <el-option label="服务态度" value="service" />
              <el-option label="环境设施" value="environment" />
            </el-select>
          </div>
        </template>
        <div ref="satisfactionChartRef" class="w-full h-full"></div>
      </el-card>
    </div>

    <!-- 风险预测分析 -->
    <el-card shadow="hover">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="font-bold">患者复诊风险预测</span>
          <div class="flex gap-2">
            <el-select v-model="riskPredictionType" class="w-32">
              <el-option label="复诊预测" value="revisit" />
              <el-option label="疾病复发" value="relapse" />
            </el-select>
            <el-button type="primary" @click="handleUpdatePrediction">
              更新预测
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="riskPredictionList" border stripe>
        <el-table-column type="expand">
          <template #default="props">
            <div class="p-4">
              <el-descriptions :column="3" border>
                <el-descriptions-item label="既往病史">
                  {{ props.row.medicalHistory }}
                </el-descriptions-item>
                <el-descriptions-item label="最近就诊">
                  {{ props.row.lastVisit }}
                </el-descriptions-item>
                <el-descriptions-item label="主要症状">
                  {{ props.row.symptoms }}
                </el-descriptions-item>
              </el-descriptions>
              <div class="mt-4">
                <div class="font-bold mb-2">风险因素分析</div>
                <el-progress
                  v-for="(factor, index) in props.row.riskFactors"
                  :key="index"
                  :percentage="factor.value"
                  :color="factor.color"
                  :format="() => factor.label"
                  class="mb-2"
                />
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="patientName" label="患者姓名" width="120" />
        <el-table-column prop="age" label="年龄" width="80" />
        <el-table-column prop="department" label="就诊科室" width="120" />
        <el-table-column prop="diagnosis" label="主要诊断" min-width="200" />
        <el-table-column prop="riskLevel" label="风险等级" width="100">
          <template #default="{ row }">
            <el-tag :type="getRiskLevelType(row.riskLevel)">
              {{ getRiskLevelLabel(row.riskLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="predictedTime" label="预计时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewDetail(row)">
              详情
            </el-button>
            <el-button type="success" link @click="handleAddIntervention(row)">
              干预计划
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 干预计划对话框 -->
    <Drawer
      v-model="showInterventionDialog"
      title="制定干预计划"
      size="600px"
      @confirm = "handleConfirmIntervention"
    >
      <el-form :model="interventionForm" label-width="100px">
        <el-form-item label="患者姓名">
          {{ selectedPatient?.patientName }}
        </el-form-item>
        <el-form-item label="风险等级">
          <el-tag :type="getRiskLevelType(selectedPatient?.riskLevel)">
            {{ getRiskLevelLabel(selectedPatient?.riskLevel) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="干预方式">
          <el-checkbox-group v-model="interventionForm.methods">
            <el-checkbox :value="'call'">电话随访</el-checkbox>
            <el-checkbox :value="'message'">短信提醒</el-checkbox>
            <el-checkbox :value="'visit'">上门随访</el-checkbox>
            <el-checkbox :value="'education'">健康教育</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="干预频率">
          <el-select v-model="interventionForm.frequency" class="w-full">
            <el-option label="每周一次" value="weekly" />
            <el-option label="每月一次" value="monthly" />
            <el-option label="每季度一次" value="quarterly" />
          </el-select>
        </el-form-item>
        <el-form-item label="干预内容">
          <el-input
            v-model="interventionForm.content"
            type="textarea"
            :rows="3"
            placeholder="请输入具体的干预计划内容"
          />
        </el-form-item>
        <el-form-item label="执行人员">
          <el-select v-model="interventionForm.executor" class="w-full">
            <el-option
              v-for="staff in medicalStaff"
              :key="staff.id"
              :label="staff.name"
              :value="staff.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </Drawer>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
// import * as echarts from 'echarts'
import Drawer from '@/components/common/Drawer.vue'

// 统计数据
const statistics = ref([
  {
    label: '本月就诊人次',
    value: '2,456',
    icon: 'User',
    color: 'text-blue-500',
    iconColor: 'text-blue-200',
    compare: '环比上月',
    trend: 'up',
    percentage: '+15.2%'
  },
  {
    label: '平均就诊频率',
    value: '3.2次',
    icon: 'Calendar',
    color: 'text-green-500',
    iconColor: 'text-green-200',
    compare: '环比上月',
    trend: 'up',
    percentage: '+5.8%'
  },
  {
    label: '平均消费金额',
    value: '￥860',
    icon: 'Money',
    color: 'text-orange-500',
    iconColor: 'text-orange-200',
    compare: '环比上月',
    trend: 'down',
    percentage: '-2.3%'
  },
  {
    label: '整体满意度',
    value: '96.5%',
    icon: 'Star',
    color: 'text-purple-500',
    iconColor: 'text-purple-200',
    compare: '环比上月',
    trend: 'up',
    percentage: '+1.2%'
  }
])

// 图表相关
const sourceChartRef = ref(null)
const frequencyChartRef = ref(null)
const consumptionChartRef = ref(null)
const satisfactionChartRef = ref(null)

// 筛选条件
const sourceTimeRange = ref('30')
const visitFrequencyType = ref('monthly')
const consumptionDepartment = ref('')
const satisfactionDimension = ref('overall')
const riskPredictionType = ref('revisit')

// 科室数据
const departments = ref([
  { id: '1', name: '内科' },
  { id: '2', name: '外科' },
  { id: '3', name: '儿科' }
])

// 医护人员数据
const medicalStaff = ref([
  { id: '1', name: '张医生' },
  { id: '2', name: '李护士' },
  { id: '3', name: '王医生' }
])

// 风险预测数据
const riskPredictionList = ref([
  {
    patientName: '张三',
    age: 45,
    department: '内科',
    diagnosis: '高血压、糖尿病',
    riskLevel: 'high',
    predictedTime: '2024-04-15',
    medicalHistory: '高血压病史10年，糖尿病5年',
    lastVisit: '2024-03-01',
    symptoms: '血压控制不稳定',
    riskFactors: [
      { label: '年龄因素', value: 75, color: '#f56c6c' },
      { label: '并发症风险', value: 85, color: '#e6a23c' },
      { label: '服药依从性', value: 60, color: '#409eff' }
    ]
  }
])

// 干预计划
const showInterventionDialog = ref(false)
const selectedPatient = ref(null)
const interventionForm = ref({
  methods: [],
  frequency: '',
  content: '',
  executor: ''
})

// 状态处理函数
const getRiskLevelType = (level) => {
  const types = {
    low: 'info',
    medium: 'warning',
    high: 'danger'
  }
  return types[level]
}

const getRiskLevelLabel = (level) => {
  const labels = {
    low: '低风险',
    medium: '中风险',
    high: '高风险'
  }
  return labels[level]
}

// 初始化图表
const initCharts = () => {
  // 患者来源渠道分析
  const sourceChart = echarts.init(sourceChartRef.value)
  sourceChart.setOption({
    title: {
      text: '患者来源分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: [
          { value: 1048, name: '线上预约' },
          { value: 735, name: '电话预约' },
          { value: 580, name: '现场挂号' },
          { value: 484, name: '转诊' },
          { value: 300, name: '其他' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })

  // 就诊频率趋势
  const frequencyChart = echarts.init(frequencyChartRef.value)
  frequencyChart.setOption({
    title: {
      text: '就诊频率趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: [150, 230, 224, 218, 135, 147],
        type: 'line',
        smooth: true
      }
    ]
  })

  // 消费金额分析
  const consumptionChart = echarts.init(consumptionChartRef.value)
  consumptionChart.setOption({
    title: {
      text: '消费金额分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['0-100', '100-500', '500-1000', '1000-2000', '2000以上']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: [120, 200, 150, 80, 70],
        type: 'bar'
      }
    ]
  })

  // 满意度分析
  const satisfactionChart = echarts.init(satisfactionChartRef.value)
  satisfactionChart.setOption({
    title: {
      text: '满意度评价',
      left: 'center'
    },
    radar: {
      indicator: [
        { name: '医疗质量', max: 100 },
        { name: '服务态度', max: 100 },
        { name: '环境设施', max: 100 },
        { name: '等待时间', max: 100 },
        { name: '收费合理', max: 100 }
      ]
    },
    series: [
      {
        type: 'radar',
        data: [
          {
            value: [95, 98, 92, 85, 90],
            name: '满意度得分'
          }
        ]
      }
    ]
  })
}

// 方法
const handleUpdatePrediction = () => {
  ElMessage.success('预测数据已更新')
}

const handleViewDetail = (row) => {
  ElMessage.success('查看详情功能待实现')
}

const handleAddIntervention = (row) => {
  selectedPatient.value = row
  showInterventionDialog.value = true
}
// 干预计划确认
const handleConfirmIntervention = () => {
  ElMessage.success('干预计划已确认')
  showInterventionDialog.value = false
}
onMounted(() => {
  // initCharts()
})
</script>

